package com.flyco.modules.pms.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.modules.pms.service.IPmsProductAttributeValueService;
import org.apache.shiro.SecurityUtils;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.pms.entity.PmsProductAttribute;
import com.flyco.modules.pms.entity.PmsProductAttributeCategory;
import com.flyco.modules.pms.vo.PmsProductAttributeCategoryPage;
import com.flyco.modules.pms.service.IPmsProductAttributeCategoryService;
import com.flyco.modules.pms.service.IPmsProductAttributeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;

 /**
 * @Description: 类型
 * @Author: flyco
 * @Date:   2019-11-18
 * @Version: V1.0
 */
@RestController
@RequestMapping("/f/pms/pmsProductAttributeCategory")
@Slf4j
public class PmsProductAttributeCategoryController {
	@Autowired
	private IPmsProductAttributeCategoryService pmsProductAttributeCategoryService;
	@Autowired
	private IPmsProductAttributeService pmsProductAttributeService;
	@Autowired
	private IPmsProductAttributeValueService pmsProductAttributeValueService;
	
	/**
	 * 分页列表查询
	 *
	 * @param pmsProductAttributeCategory
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<?> queryPageList(PmsProductAttributeCategory pmsProductAttributeCategory,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<PmsProductAttributeCategory> queryWrapper = QueryGenerator.initQueryWrapper(pmsProductAttributeCategory, req.getParameterMap());
		Page<PmsProductAttributeCategory> page = new Page<PmsProductAttributeCategory>(pageNo, pageSize);
		IPage<PmsProductAttributeCategory> pageList = pmsProductAttributeCategoryService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param pmsProductAttributeCategoryPage
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody PmsProductAttributeCategoryPage pmsProductAttributeCategoryPage) {
        PmsProductAttributeCategory pmsProductAttributeCategory = new PmsProductAttributeCategory();
		BeanUtils.copyProperties(pmsProductAttributeCategoryPage, pmsProductAttributeCategory);
		pmsProductAttributeCategoryService.save(pmsProductAttributeCategory);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param pmsProductAttributeCategoryPage
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody PmsProductAttributeCategoryPage pmsProductAttributeCategoryPage) {
		PmsProductAttributeCategory pmsProductAttributeCategory = new PmsProductAttributeCategory();
		BeanUtils.copyProperties(pmsProductAttributeCategoryPage, pmsProductAttributeCategory);
		pmsProductAttributeCategoryService.updateById(pmsProductAttributeCategory);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) Long id) {
		pmsProductAttributeCategoryService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
	    this.pmsProductAttributeCategoryService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		PmsProductAttributeCategory pmsProductAttributeCategory = pmsProductAttributeCategoryService.getById(id);
		return Result.ok(pmsProductAttributeCategory);
	}
	
	//===========================以下是子表信息操作相关API====================================

	 /**
	  * 子表新增、删除时，更新主表属性数量与参数数量
	  * @param mainId
	  */
	 private void updateCount(long mainId){
		 LambdaQueryWrapper<PmsProductAttribute> attrQuery = new LambdaQueryWrapper<>();
		 attrQuery.eq(PmsProductAttribute::getProductAttributeCategoryId, mainId);
		 attrQuery.eq(PmsProductAttribute::getType,"0");
		 int attrCount = pmsProductAttributeService.count(attrQuery);
		 LambdaQueryWrapper<PmsProductAttribute> paramQuery = new LambdaQueryWrapper<>();
		 paramQuery.eq(PmsProductAttribute::getProductAttributeCategoryId, mainId);
		 paramQuery.eq(PmsProductAttribute::getType,"1");
		 int paramCount = pmsProductAttributeService.count(paramQuery);
		 PmsProductAttributeCategory pmsProductAttributeCategory = new PmsProductAttributeCategory();
		 pmsProductAttributeCategory.setId(mainId);
		 pmsProductAttributeCategory.setAttributeCount(attrCount);
		 pmsProductAttributeCategory.setParamCount(paramCount);
		 pmsProductAttributeCategoryService.updateById(pmsProductAttributeCategory);
	 }
	
	/**
	 * 通过主表id查询属性
	 *
  	 * @param pmsProductAttribute
	 * @return
	 */
	@GetMapping(value = "/listPmsProductAttributeByMainId")
	public Result<?> listPmsProductAttributeByMainId(PmsProductAttribute pmsProductAttribute,
                								  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                								  HttpServletRequest req) {
        if(pmsProductAttribute.getProductAttributeCategoryId()!=null) {
            QueryWrapper<PmsProductAttribute> queryWrapper = QueryGenerator.initQueryWrapper(pmsProductAttribute, req.getParameterMap());
            Page<PmsProductAttribute> page = new Page<PmsProductAttribute>(pageNo, pageSize);
            IPage<PmsProductAttribute> pageList =  pmsProductAttributeService.page(page, queryWrapper);
            return Result.ok(pageList);
        }else{
            return Result.error("");
        }
    }
	
	/**
     * 添加属性
     *
     * @param pmsProductAttribute
     * @return
     */
    @PostMapping(value = "/addPmsProductAttribute")
    public Result<?> addPmsProductAttribute(@RequestBody PmsProductAttribute pmsProductAttribute) {
        pmsProductAttributeService.save(pmsProductAttribute);
		updateCount(pmsProductAttribute.getProductAttributeCategoryId());
        return Result.ok("添加属性成功！");
    }
    
    /**
     * 编辑属性
     *
     * @param pmsProductAttribute
     * @return
     */
    @PutMapping("/editPmsProductAttribute")
    public Result<?> editPmsProductAttribute(@RequestBody PmsProductAttribute pmsProductAttribute) {
        pmsProductAttributeService.updateById(pmsProductAttribute);
        return Result.ok("编辑属性成功！");
    }
    
    /**
     * 通过id删除属性
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/deletePmsProductAttribute")
    public Result<?> deletePmsProductAttribute(@RequestParam(name = "id", required = true) String id) {
		Long productAttributeCategoryId = pmsProductAttributeService.getById(id).getProductAttributeCategoryId();
		pmsProductAttributeService.removeById(id);
		pmsProductAttributeValueService.deleteByAttributeId(Long.valueOf(id));
		updateCount(productAttributeCategoryId);
        return Result.ok("删除属性成功！");
    }
	
	/**
     * 批量删除属性
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatchPmsProductAttribute")
    public Result<?> deleteBatchPmsProductAttribute(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        }
		Long productAttributeCategoryId = pmsProductAttributeService.getById(Arrays.asList(ids.split(",")).get(0)).getProductAttributeCategoryId();
        this.pmsProductAttributeService.removeByIds(Arrays.asList(ids.split(",")));
		updateCount(productAttributeCategoryId);
       	return Result.ok("批量删除成功！");

    }
    

    /**
    * 导出excel
    *
    * @param request
    * @param pmsProductAttributeCategory
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PmsProductAttributeCategory pmsProductAttributeCategory) {
      // Step.1 组装查询条件
      QueryWrapper<PmsProductAttributeCategory> queryWrapper = QueryGenerator.initQueryWrapper(pmsProductAttributeCategory, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<PmsProductAttributeCategoryPage> pageList = new ArrayList<PmsProductAttributeCategoryPage>();
      List<PmsProductAttributeCategory> pmsProductAttributeCategoryList = pmsProductAttributeCategoryService.list(queryWrapper);
      for (PmsProductAttributeCategory temp : pmsProductAttributeCategoryList) {
          PmsProductAttributeCategoryPage vo = new PmsProductAttributeCategoryPage();
          BeanUtils.copyProperties(temp, vo);
          List<PmsProductAttribute> pmsProductAttributeList = pmsProductAttributeService.selectByMainId(temp.getId());
          vo.setPmsProductAttributeList(pmsProductAttributeList);
          pageList.add(vo);
      }
      //Step.3 调用AutoPoi导出Excel
      ModelAndView mv = new ModelAndView(new EntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "类型");
      mv.addObject(NormalExcelConstants.CLASS, PmsProductAttributeCategoryPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("类型数据", "导出人:"+sysUser.getRealname(), "类型"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<PmsProductAttributeCategoryPage> list = ExcelImportUtil.importExcel(file.getInputStream(), PmsProductAttributeCategoryPage.class, params);
              for (PmsProductAttributeCategoryPage page : list) {
                  PmsProductAttributeCategory po = new PmsProductAttributeCategory();
                  BeanUtils.copyProperties(page, po);
                  pmsProductAttributeCategoryService.saveMain(po, page.getPmsProductAttributeList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }
}
